package com.com.knowledgepaymentmanagementsystem.service.assets.impl;

import com.com.knowledgepaymentmanagementsystem.mapper.assets.AssetsMapper;
import com.com.knowledgepaymentmanagementsystem.pojo.assets.Assets;
import com.com.knowledgepaymentmanagementsystem.pojo.courseshop.CourseShop;
import com.com.knowledgepaymentmanagementsystem.service.assets.AssetsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 张攀
 * @version 1.0
 * @description: TODO
 * @date 2025/9/23 上午10:48
 */
@Service
public class AssetsServiceImpl implements AssetsService {

    @Autowired
    private AssetsMapper assetsMapper;
    @Override
    public List<Assets> selectAssets(Assets assets) {
        return assetsMapper.selectAssets(assets);
    }

    @Override
    public Object insertAssets(Assets assets) {
        assets.setCreateTime(LocalDateTime.now());
        return assetsMapper.insert(assets);
    }

    @Override
    public void updateAssets(Assets assets) {
        assetsMapper.updateById(assets);
    }

    @Override
    public void deleteAsses(Integer id) {
        assetsMapper.deleteById(id);
    }

    @Override
    public void insertShopAssets(CourseShop courseShop) {
        Assets assets = new Assets();
        assets.setIncomeType(1);
        assets.setAssetsType(1);
        assets.setAssetsPrice(courseShop.getPrice());
        // 查询当前最新余额
        Double currentBalance = getLatestBalance();
        // 计算新余额（当前余额 + 新收入）
        Double newBalance = (currentBalance != null ?
                currentBalance : 0.0) + courseShop.getPrice();
        assets.setAssetsBalance(newBalance);
        assets.setAssetsAbstract(courseShop.getName());
        assets.setCreateTime(LocalDateTime.now());
        assetsMapper.insert(assets);
    }


    private Double getLatestBalance() {
        // 查询最新的余额记录
        Assets latestAssets = assetsMapper.selectLatest();
        return latestAssets != null ? latestAssets.getAssetsBalance() : null;
    }
}
